/**
 * Crazy Upload
 *  License by CrazyYi.
 *  v1.0.0 20200206
 *  v1.1.0 20200227: 支持多个upload组件
 *
 *  Only use for file upload: excel, word, image
 *
 */
layui.define(['table', 'jquery', 'upload', 'crazyTool'], function (exports) {
    const MOD_NAME = 'crazyUpload'

    let $ = layui.jquery,
        crazyTool = layui.crazyTool,
        upload = layui.upload;

    let gTbId = ''; // table elem id

    let gMainTable = {};

    const defaultOptions = {
        elem: undefined,   //绑定元素
        url: undefined, //上传接口
        accept: 'file', // 对应后台代码中的action
        exts: "xls|xlsx",
        field: "file",
        acceptMime: "file/xls,file/xlsx",
        previewId: undefined,

        before: function (obj) {
            console.log('upload before', obj);
            let othis = this;
            // 预读本地文件示例，不支持ie8
            if (!!othis.previewId) {
                obj.preview(function (index, file, result) {
                    $('#' + othis.previewId).attr('src', result); //图片链接（base64）
                });
            }
        },
        done: function (res) {
            console.log('upload done', res);
            //上传完毕回调
            let othis = this;

            if (res.code == 0) {
                layer.confirm(res.msg, {btn: ['确定']}
                    , function (index) {
                        // 20200226，改成采用 回调函数的方法进行处理
                        othis.success && typeof othis.success === 'function' && othis.success(gMainTable, res);
                        layer.close(index);
                    });

                // layer.msg('上传成功');

                // table.reload(gMainTable.id, gMainTable);
            } else {
                layer.msg('上传失败=' + res.msg);
            }
        },
        error: function (index, upload) {
            console.log('upload error', upload);
            //请求异常回调
            layer.msg('很抱歉，上传出现异常，请联系技术人员');
        },
        success: function (options, res) {

        },
    };
    let gOptions = []; // 20200227，支持多个upload组件

    //执行实例
    const uploadIns = {
        Excel: function () {
            $.each(gOptions, function (i, option) {
                upload.render(option);
            });
        },
    };

    let dataIns = {
        render: function (myTable) {
            console.log('--------- crazyTable Upload ------------------', myTable);
            gMainTable = myTable;
            gOptions = []; // 每次赋值前，需要先清空
            $.each(gMainTable.upload, function (i, option) {
                let nOpt = {};
                $.extend(nOpt, defaultOptions, option);
                gOptions.push(nOpt);
            });
            // $.extend(gOptions, defaultOptions);
            // $.extend(gOptions, gMainTable.upload);
            gTbId = gMainTable.id;
            console.log('init configs', gOptions);

            uploadIns.Excel();
        },

    };

    /**
     * 输出接口 gTable
     */
    exports(MOD_NAME, dataIns);
});